/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "memory/rs_memory_snapshot.h"
#include "render/rs_image_cache.h"
#include "pixel_map.h"

namespace Keels {
namespace Rosen {
// modify the RSImageCache instance as global to extend life cycle, fix destructor crash

void ClearRSImageCache()
{
    RSImageCache::Instance().Clear();
}

RSImageCache& RSImageCache::Instance()
{
    static RSImageCache instance;
    return instance;
}

void RSImageCache::CacheDrawingImage(uint64_t uniqueId, std::shared_ptr<Drawing::Image> img)
{
    if (img && uniqueId > 0) {
        std::lock_guard<std::mutex> lock(mutex_);
        drawingImageCache_.emplace(uniqueId, std::make_pair(img, 0));
    }
}

std::shared_ptr<Drawing::Image> RSImageCache::GetDrawingImageCache(uint64_t uniqueId) const
{
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = drawingImageCache_.find(uniqueId);
    if (it != drawingImageCache_.end()) {
        return it->second.first;
    }
    return nullptr;
}

void RSImageCache::IncreaseDrawingImageCacheRefCount(uint64_t uniqueId)
{
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = drawingImageCache_.find(uniqueId);
    if (it != drawingImageCache_.end()) {
        it->second.second++;
    }
}

void RSImageCache::ReleaseDrawingImageCache(uint64_t uniqueId)
{
    // release the Drawing::Image if no RSImage holds it
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = drawingImageCache_.find(uniqueId);
    if (it != drawingImageCache_.end()) {
        it->second.second--;
        if (it->second.first == nullptr || it->second.second == 0) {
            drawingImageCache_.erase(it);
        }
    }
}

void RSImageCache::CachePixelMap(uint64_t uniqueId, std::shared_ptr<Media::PixelMap> pixelMap)
{
    if (pixelMap && uniqueId > 0) {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            pixelMapCache_.emplace(uniqueId, std::make_pair(pixelMap, 0));
        }
        auto type = pixelMap->GetAllocatorType();
        pid_t pid = uniqueId >> 32; // right shift 32 bit to restore pid
        if (type != Media::AllocatorType::DMA_ALLOC && pid) {
            auto realSize = type == Media::AllocatorType::SHARE_MEM_ALLOC
                                ? pixelMap->GetCapacity() / 2 // rs only counts half of the SHARE_MEM_ALLOC memory
                                : pixelMap->GetCapacity();
            MemorySnapshot::Instance().AddCpuMemory(pid, realSize);
        }
    }
}

std::shared_ptr<Media::PixelMap> RSImageCache::GetPixelMapCache(uint64_t uniqueId) const
{
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = pixelMapCache_.find(uniqueId);
    if (it != pixelMapCache_.end()) {
        return it->second.first;
    }
    return nullptr;
}

void RSImageCache::IncreasePixelMapCacheRefCount(uint64_t uniqueId)
{
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = pixelMapCache_.find(uniqueId);
    if (it != pixelMapCache_.end()) {
        it->second.second++;
    }
}

void RSImageCache::CollectUniqueId(uint64_t uniqueId)
{
    std::unique_lock<std::mutex> lock(uniqueIdListMutex_);
    uniqueIdList_.insert(uniqueId);
}

void RSImageCache::ReleaseUniqueIdList()
{
    if (pixelMapIdRelatedDrawingImageCacheSize_ < pixelMapIdRelatedDrawingImageCacheLimit_) {
        return;
    }
    // std::string msg = "ReleaseUniqueIdList " + std::to_string(pixelMapIdRelatedDrawingImageCacheSize_) + "/" +
    // std::to_string(pixelMapIdRelatedDrawingImageCacheLimit_); RS_TRACE_NAME(msg.c_str());
    std::vector<std::pair<uint64_t, pid_t>> ids;
    {
        std::lock_guard<std::mutex> lock(mapMutex_);
        while (pixelMapIdRelatedDrawingImageCacheSize_ * 2 > pixelMapIdRelatedDrawingImageCacheLimit_) {
            auto uid = std::get<0>(pixelMapIdRelatedDrawingImageCacheList_.back());
            auto tid = std::get<1>(pixelMapIdRelatedDrawingImageCacheList_.back());
            auto size = std::get<3>(pixelMapIdRelatedDrawingImageCacheList_.back());
            pixelMapIdRelatedDrawingImageCacheList_.pop_back();
            ids.push_back(std::make_pair(uid, tid));
            pixelMapIdRelatedDrawingImageCacheSize_ -= size;
        }
    }
    {
        std::unique_lock<std::mutex> lock(uniqueIdListMutex_);
        for (auto& id : ids) {
            uniqueIdList_.erase(id.first);
        }
    }
    for (auto& id : ids) {
        ReleasePixelMapCache(id.first, id.second);
    }
}

void RSImageCache::Clear()
{
    std::vector<std::pair<uint64_t, pid_t>> ids;
    {
        std::lock_guard<std::mutex> lock(mapMutex_);
        while (pixelMapIdRelatedDrawingImageCacheList_.empty() == false) {
            auto uid = std::get<UID_IDX>(pixelMapIdRelatedDrawingImageCacheList_.back());
            auto tid = std::get<TID_IDX>(pixelMapIdRelatedDrawingImageCacheList_.back());
            auto size = std::get<SIZE_IDX>(pixelMapIdRelatedDrawingImageCacheList_.back());
            pixelMapIdRelatedDrawingImageCacheList_.pop_back();
            ids.push_back(std::make_pair(uid, tid));
        }
        pixelMapIdRelatedDrawingImageCacheSize_ = 0;
    }
    {
        std::unique_lock<std::mutex> lock(uniqueIdListMutex_);
        for (auto& id : ids) {
            uniqueIdList_.erase(id.first);
        }
    }
    for (auto& id : ids) {
        ReleasePixelMapCache(id.first, id.second);
    }
}

bool RSImageCache::CheckUniqueIdIsEmpty()
{
    if (uniqueIdListMutex_.try_lock()) {
        if (uniqueIdList_.empty()) {
            uniqueIdListMutex_.unlock();
            return true;
        }
        uniqueIdListMutex_.unlock();
    }
    return false;
}

void RSImageCache::ReleasePixelMapCache(uint64_t uniqueId, pid_t tid)
{
    std::shared_ptr<Media::PixelMap> pixelMap = nullptr;
    {
        // release the pixelMap if no RSImage holds it
        std::lock_guard<std::mutex> lock(mutex_);
        auto it = pixelMapCache_.find(uniqueId);
        if (it != pixelMapCache_.end()) {
            it->second.second--;
            if (it->second.first == nullptr || it->second.second == 0) {
                pixelMap = it->second.first;
                bool shouldCount = pixelMap && pixelMap->GetAllocatorType() != Media::AllocatorType::DMA_ALLOC;
                pid_t pid = uniqueId >> 32; // right shift 32 bit to restore pid
                if (shouldCount && pid) {
                    auto realSize =
                        pixelMap->GetAllocatorType() == Media::AllocatorType::SHARE_MEM_ALLOC
                            ? pixelMap->GetCapacity() / 2 // rs only counts half of the SHARE_MEM_ALLOC memory
                            : pixelMap->GetCapacity();
                    MemorySnapshot::Instance().RemoveCpuMemory(pid, realSize);
                }
                pixelMapCache_.erase(it);
                ReleaseDrawingImageCacheByPixelMapId(uniqueId, tid);
            }
        }
        ReleaseDrawingImageCacheByPixelMapId(uniqueId, tid);
    }
    pixelMap.reset();
}

void RSImageCache::CacheRenderDrawingImageByPixelMapId(
    uint64_t uniqueId, std::shared_ptr<Drawing::Image> img, pid_t tid)
{
    if (uniqueId > 0 && img) {
        std::lock_guard<std::mutex> lock(mapMutex_);
        auto it = pixelMapIdRelatedDrawingImageCache_.find(uniqueId);
        if (it != pixelMapIdRelatedDrawingImageCache_.end()) {
            auto innerIt = it->second.find(tid);
            if (innerIt != it->second.end()) {
                return;
            }
        }
        auto info = img->GetImageInfo();
        size_t size = info.GetHeight() * info.GetWidth() * info.GetBytesPerPixel();
        pixelMapIdRelatedDrawingImageCacheList_.emplace_front(std::make_tuple(uniqueId, tid, img, size));
        pixelMapIdRelatedDrawingImageCacheSize_ += size;
        pixelMapIdRelatedDrawingImageCache_[uniqueId][tid] = pixelMapIdRelatedDrawingImageCacheList_.begin();
    }
}

std::shared_ptr<Drawing::Image> RSImageCache::GetRenderDrawingImageCacheByPixelMapId(uint64_t uniqueId, pid_t tid) const
{
    std::lock_guard<std::mutex> lock(mapMutex_);
    auto it = pixelMapIdRelatedDrawingImageCache_.find(uniqueId);
    if (it != pixelMapIdRelatedDrawingImageCache_.end()) {
        auto innerIt = it->second.find(tid);
        if (innerIt != it->second.end()) {
            pixelMapIdRelatedDrawingImageCacheList_.splice(pixelMapIdRelatedDrawingImageCacheList_.begin(),
                pixelMapIdRelatedDrawingImageCacheList_, innerIt->second);
            return std::get<IMG_IDX>(*(innerIt->second));
        }
    }
    return nullptr;
}

void RSImageCache::ReleaseDrawingImageCacheByPixelMapId(uint64_t uniqueId, pid_t tid)
{
    std::lock_guard<std::mutex> lock(mapMutex_);
    auto it = pixelMapIdRelatedDrawingImageCache_.find(uniqueId);
    if (it != pixelMapIdRelatedDrawingImageCache_.end()) {
        if (tid == -1) {
            pixelMapIdRelatedDrawingImageCache_.erase(it);
        } else {
            it->second.erase(tid);
            if (it->second.empty()) {
                pixelMapIdRelatedDrawingImageCache_.erase(it);
            }
        }
    }
}
} // namespace Rosen
} // namespace Keels
